package com.lagou.util;

import com.lagou.domain.Student;
import com.lagou.domain.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;

public class TestJDBCUtils {

    // 获取连接池对象
    DataSource dataSource = JDBCUtils.getDataSource();

    // 创建QueryRunner对象
    QueryRunner qr = new QueryRunner(dataSource);

    // 查询数据
    @Test
    public void test_query() throws SQLException {

        String sql = "SELECT * FROM User WHERE username = ? and password = ?";
        String name = "sunwukong";
        String pwd = "123";
        /*Object[] res = qr.query(sql, new ArrayHandler(), name, pwd);
        if (res.length > 0) {
            System.out.println(Arrays.toString(res));
        }else {
            System.out.println("对不起，不存在该用户");
        }*/
        User res = qr.query(sql, new BeanHandler<User>(User.class), name, pwd);

        if(null != res) {
            System.out.println(res.getUsername() + " 欢迎您！！");
        } else {
            System.out.println("账号或密码输入有误!!");
        }
    }


    // 插入数据
    @Test
    public void test_insert() throws SQLException {


        String sql = "INSERT INTO Student VALUES (?, ?, ?, ?)";
        Student s = qr.insert(sql, new BeanHandler<Student>(Student.class), 1001, "李晓梅", "0", new Date("2010/12/01"));
        System.out.println(s);
    }
}
